﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Transactions;
using ZenSystemService.Api.Business;
using ZenSystemService.Api.Common;
using ZenSystemService.Api.Common.Auth;
using ZenSystemService.Api.DTOs;
using ZenSystemService.Api.DTOs.Institution;
using ZenSystemService.Api.DTOs.Users;
using ZenSystemService.Api.Entities;
using ZenSystemService.Api.Migrations;
using ZenSystemService.Api.Services;

namespace ZenSystemService.Api.Controllers
{
    [Route("api/institutions")]
    [ApiController]
    //[Authorize(Roles = "Admin")] // 只允许Admin角色访问
    public class InstitutionController : ControllerBase
    {
        private readonly InstitutionService _institutionService;
        private readonly SMSVerificationCodeService _smsVerificationCodeService;
        private readonly UserService _userService;
        private readonly UserRoleService _userRoleService;
        private readonly RoleService _roleService;
        private readonly TencentAccessTokenService _tencentAccessTokenService;
        private readonly AppletsInterfaceBusiness _appletsInterfaceBusiness;
        private readonly DTOBusiness _dTOBusiness;
        private readonly TokenService _tokenService;
        public InstitutionController(InstitutionService institutionService,SMSVerificationCodeService smsVerificationCodeService
            , UserService userService, UserRoleService userRoleService, RoleService roleService, TencentAccessTokenService tencentAccessTokenService
            , AppletsInterfaceBusiness appletsInterfaceBusiness, DTOBusiness dTOBusiness, TokenService tokenService)
        {
            _institutionService = institutionService;
            _smsVerificationCodeService = smsVerificationCodeService;
            _userService = userService;
            _userRoleService = userRoleService;
            _roleService = roleService;
            _tencentAccessTokenService= tencentAccessTokenService;
            _appletsInterfaceBusiness = appletsInterfaceBusiness;
            _dTOBusiness = dTOBusiness;
            _tokenService = tokenService;
        }

        /*
        /// <summary>
        /// 机构注册登录
        /// </summary>
        /// <param name="_receiveObject"></param>
        /// <returns></returns>
        [HttpPost("InstitutionRegisterLogin")]
        public async Task<ReturnObjectT<InstitutionForeLoginResponse>> InstitutionRegisterLogin(ReceiveObjectT<InstitutionForeLoginRequest> _receiveObject)
        {
            ReturnObjectT<InstitutionForeLoginResponse> _returnObject = new ReturnObjectT<InstitutionForeLoginResponse>();

            //判断验证码信息
            string phone = _receiveObject.Data.Phone;
            string code = _receiveObject.Data.VerificationCode;
            bool isSuccess = await _smsVerificationCodeService.ValidateVerificationCode(phone, code);
            if (isSuccess==false)
            {
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "验证码信息不匹配或已过期";
                return _returnObject;
            }

            //根据手机号判断 用户是否已存在
            User _user  = await _userService.GetUserByPhoneAsync(phone);
            InstitutionForeLoginResponse _institutionForeLoginResponse = new InstitutionForeLoginResponse();

            if (_user == null)
            {
                _institutionForeLoginResponse.InstitutionIsExist = false;
            }
            else
            {
                //返回机构信息 用户信息
                _institutionForeLoginResponse.InstitutionIsExist = true;
                _institutionForeLoginResponse.UserInfo = _user;
                if (_user.InstitutionId.HasValue)
                    _institutionForeLoginResponse.InstitutionInfo = await _institutionService.GetInstitutionByIdAsync(_user.InstitutionId.Value);
            }
            _returnObject.Code = 1;
            _returnObject.Data = _institutionForeLoginResponse;
            return _returnObject;
        }
        */

        /*
        /// <summary>
        /// 机构注册信息登记
        /// </summary>
        /// <param name="_receiveObject"></param>
        /// <returns></returns>
        [HttpPost("InstitutionRegisterInfoEnroll")]
        public async Task<ReturnObjectT<InstitutionForeLoginResponse>> InstitutionRegisterInfoEnroll(ReceiveObjectT<InstitutionRegisterInfo> _receiveObject)
        {
            ReturnObjectT<InstitutionForeLoginResponse> _returnObject = new ReturnObjectT<InstitutionForeLoginResponse>();

            InstitutionRegisterInfo _institutionRegisterInfo = _receiveObject.Data;
            User queryUser = await _userService.GetUserByPhoneAsync(_institutionRegisterInfo.Phone);
            if (queryUser != null)
            {
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "该手机号已存在用户信息";
                return _returnObject;
            }

            using (TransactionScope transScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                //机构信息
                Institution _institution = new Institution();
                _institution.InstitutionType = _institutionRegisterInfo.InstitutionType;
                _institution.Name = _institutionRegisterInfo.Name;
                _institution.Enabled = "1";
                _institution.PhoneNo = _institutionRegisterInfo.Phone;
                _institution.Representative = _institutionRegisterInfo.ContactsName;
                _institution.RepresentativePhoneNo = _institutionRegisterInfo.Phone;
                _institution.RepresentativeTitle = _institutionRegisterInfo.ContactsPosition;
                _institution.AreaId = _institutionRegisterInfo.AreaId;
                if (!_institutionService.CreateInstitutionAsync(ref _institution))
                {
                    _returnObject.Code = 0;
                    _returnObject.ErrorMsg = "创建机构信息错误";
                    return _returnObject;
                }

                //用户信息
                User _user = new User();
                string password = _institutionRegisterInfo.Password;
                _user.Username = _institutionRegisterInfo.ContactsName;
                _user.InstitutionId = _institution.InstitutionId;
                _user.UserType = ((int)UserType.Institution).ToString();
                _user.Mobile = _institutionRegisterInfo.Phone;
                _user.Enabled = "1";
                _user.CreatedDate = DateTime.Now;
                if (!_userService.CreateUserAsync(ref _user, password))
                {
                    _returnObject.Code = 0;
                    _returnObject.ErrorMsg = "创建用户信息错误";
                    return _returnObject;
                }


                //用户角色信息
                Role _role = await _roleService.GetRoleByNameAsync("Admin");
                if (_role == null)
                {
                    _returnObject.Code = 0;
                    _returnObject.ErrorMsg = "未取到默认管理员角色信息";
                    return _returnObject;
                }
                bool saveUserRoleIsSuccess = await _userRoleService.AssignRoleToUserAsync(_user.UserId, _role.Id);
                if (saveUserRoleIsSuccess == false)
                {
                    _returnObject.Code = 0;
                    _returnObject.ErrorMsg = "保存用户角色信息失败";
                    return _returnObject;
                }

                transScope.Complete();


                //返回机构信息 用户信息
                InstitutionForeLoginResponse _institutionForeLoginResponse = new InstitutionForeLoginResponse();
                _institutionForeLoginResponse.InstitutionIsExist = true;
                _institutionForeLoginResponse.InstitutionInfo = _institution;
                _institutionForeLoginResponse.UserInfo = _user;
                _returnObject.Data = _institutionForeLoginResponse;
            }
            _returnObject.Code = 1;
            return _returnObject;
        }
        */



        /// <summary>
        /// 机构验证码登录
        /// </summary>0
        /// <param name="_receiveObject"></param>
        /// <returns></returns>
        [HttpPost("InstitutionVerificationCodeLogin")]
        public async Task<ReturnObjectT<InstitutionForeLoginResponse>> InstitutionVerificationCodeLogin(ReceiveObjectT<InstitutionForeLoginRequest> _receiveObject)
        {
            ReturnObjectT<InstitutionForeLoginResponse> _returnObject = new ReturnObjectT<InstitutionForeLoginResponse>();
            //判断验证码信息
            string phone = _receiveObject.Data.Phone;
            string code = _receiveObject.Data.VerificationCode;
            bool isSuccess = await _smsVerificationCodeService.ValidateVerificationCode(phone, code);
            if (isSuccess == false)
            {
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "验证码信息不匹配或已过期";
                return _returnObject;
            }

            //根据手机号判断 用户是否已存在
            User _user = await _userService.GetInstitutionUserByPhoneAsync(phone);
            InstitutionForeLoginResponse _institutionForeLoginResponse = new InstitutionForeLoginResponse();
            if (_user == null)
            {
                _institutionForeLoginResponse.InstitutionIsExist = false;
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "用户信息不存在";
                _returnObject.Data = _institutionForeLoginResponse;
                return _returnObject;
            }
            else
            {
                //返回机构信息 用户信息
                _institutionForeLoginResponse.UserInfo = await _dTOBusiness.ReorganizeUserInfoResponseDTO(_user);
                if (_user.InstitutionId.HasValue && _user.UserType == ((int)UserType.Institution).ToString())
                {
                    _institutionForeLoginResponse.InstitutionIsExist = true;
                    Institution _institution = await _institutionService.GetInstitutionByIdAsync(_user.InstitutionId.Value);
                    _institutionForeLoginResponse.InstitutionInfo = _dTOBusiness.ReorganizeInstitutionResponseDTO(_institution);
                    _institutionForeLoginResponse.UserToken = _tokenService.GenerateToken(_user);
                    _returnObject.Data = _institutionForeLoginResponse;
                    _returnObject.Code = 1;
                    return _returnObject;
                }
                else
                {
                    _institutionForeLoginResponse.InstitutionIsExist = false;
                    _returnObject.Code = 0;
                    _returnObject.ErrorMsg = "该用户信息非机构用户";
                    _returnObject.Data = _institutionForeLoginResponse;
                    return _returnObject;
                }

            }
        }



        /// <summary>
        /// 机构小程序登录
        /// </summary>
        /// <param name="_receiveObject"></param>
        /// <returns></returns>
        [HttpPost("InstitutionAppletLogin")]
        public async Task<ReturnObjectT<InstitutionForeLoginResponse>> InstitutionAppletLogin(ReceiveObjectT<InstitutionAppletLoginRequest> _receiveObject)
        {
            ReturnObjectT<InstitutionForeLoginResponse> _returnObject = new ReturnObjectT<InstitutionForeLoginResponse>();

            
            string code = _receiveObject.Data.Code;
            string msg;
            
            AppletsUserPhoneReceive appletsUserPhoneReceive = _appletsInterfaceBusiness.GetAppletsUserPhoneInfo("1",code,out msg);
            if (appletsUserPhoneReceive == null)
            {
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "获取手机号失败";
                return _returnObject;
            }
            if (appletsUserPhoneReceive.errcode != 0)
            {
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = appletsUserPhoneReceive.errmsg;
                return _returnObject;
            }
            
            
            string phone = appletsUserPhoneReceive.phone_info.purePhoneNumber;
            // string phone = "13916060126";
            //根据手机号判断 用户是否已存在
            User _user = await _userService.GetInstitutionUserByPhoneAsync(phone);
            InstitutionForeLoginResponse _institutionForeLoginResponse = new InstitutionForeLoginResponse();
            if (_user == null)
            {
                _institutionForeLoginResponse.InstitutionIsExist = false;
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "用户信息不存在";
                _returnObject.Data = _institutionForeLoginResponse;
                return _returnObject;
            }
            else
            {
                //返回机构信息 用户信息
                _institutionForeLoginResponse.UserInfo = await _dTOBusiness.ReorganizeUserInfoResponseDTO(_user);
                if (_user.InstitutionId.HasValue && _user.UserType == ((int)UserType.Institution).ToString())
                {
                    _institutionForeLoginResponse.InstitutionIsExist = true;
                    Institution _institution = await _institutionService.GetInstitutionByIdAsync(_user.InstitutionId.Value);
                    _institutionForeLoginResponse.InstitutionInfo = _dTOBusiness.ReorganizeInstitutionResponseDTO(_institution);
                    _returnObject.Code = 1;
                    _institutionForeLoginResponse.UserToken = _tokenService.GenerateToken(_user);
                    _returnObject.Data = _institutionForeLoginResponse;
                    return _returnObject;
                }
                else
                {
                    _institutionForeLoginResponse.InstitutionIsExist = false;
                    _returnObject.Code = 0;
                    _returnObject.ErrorMsg = "该用户信息非机构用户";
                    _returnObject.Data = _institutionForeLoginResponse;
                    return _returnObject;
                }

            }

        }


       


        /// <summary>
        /// 得到所有机构信息
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetAllInstitutions")]
        public async Task<ReturnObjectT<IEnumerable<Institution>>> GetAllInstitutions(ReceiveObject _receiveObject)
        {
            ReturnObjectT<IEnumerable<Institution>> _returnObject = new ReturnObjectT<IEnumerable<Institution>>();
            var user = User.ToUserModel();

            var institutions = await _institutionService.GetAllInstitutionsAsync(user);
            _returnObject.Code = 1;
            _returnObject.Data = institutions;
            //return Ok(institutions);
            return _returnObject;
        }

        /// <summary>
        /// 得到机构实体信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost("GetInstitutionById")]
        public async Task<ReturnObjectT<Institution>> GetInstitutionById(ReceiveObjectT<int> _receiveObjectT)
        {
            ReturnObjectT<Institution> _returnObject = new ReturnObjectT<Institution>();

            
            int id = _receiveObjectT.Data;
            var institution = await _institutionService.GetInstitutionByIdAsync(id);
            if (institution == null)
            {
                //return NotFound();
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "获取机构信息失败";
            }
            else
            {
                _returnObject.Code = 1;
                _returnObject.Data = institution;
            }
            return _returnObject;
            // return Ok(institution);
        }

        /// <summary>
        /// 创建机构信息
        /// </summary>
        /// <param name="institution"></param>
        /// <returns></returns>
        [HttpPost("CreateInstitution")]
        public async Task<ReturnObjectT<Institution>> CreateInstitution(ReceiveObjectT<Institution> _receiveObjectT)
        {
            ReturnObjectT<Institution> _returnObject = new ReturnObjectT<Institution>();

            
            Institution institution = _receiveObjectT.Data;
            bool isSuccess = _institutionService.CreateInstitutionAsync(ref institution);
            if (isSuccess)
            {
                _returnObject.Code = 1;
                _returnObject.Data = institution;
            }
            else
            {
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "创建机构信息失败";
            }
            return _returnObject;
            // return CreatedAtAction(nameof(GetInstitutionById), new { id = institution.InstitutionId }, institution);
        }

        /// <summary>
        /// 创建机构信息
        /// </summary>
        /// <param name="Institution"></param>
        /// <returns></returns>
        [HttpPost("Create")]
        public async Task<IActionResult> CreateInstitution(InstitutionCreateRequestDTO institution)
        {
            var admin = await _institutionService.CreateInstitutionAsync(institution);
            if (admin != null)
            {
                return CreatedAtAction(nameof(GetInstitutionById),
                new { id = admin.UserId }, admin);
            }
            else
            {
                return BadRequest("Create institution failed");
            }
        }

        /// <summary>
        /// 更新机构信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="institution"></param>
        /// <returns></returns>
        [HttpPost("UpdateInstitution")]
        public async Task<ReturnObject> UpdateInstitution(ReceiveObjectT<Institution> _receiveObjectT)
        {
            /*
            if (id != institution.InstitutionId)
            {
                return BadRequest();
            }
            */
            ReturnObject _returnObject = new ReturnObject();

            

            Institution institution = _receiveObjectT.Data;
            bool isSuccess = await _institutionService.UpdateInstitutionAsync(institution);
            if (isSuccess)
            {
                _returnObject.Code = 1;
            }
            else
            {
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "更新机构信息失败";
            }
            return _returnObject;
            //return NoContent();
        }

        /// <summary>
        /// 删除机构信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost("DeleteInstitution")]
        public async Task<ReturnObject> DeleteInstitution(ReceiveObjectT<int> _receiveObjectT)
        {
            ReturnObject _returnObject = new ReturnObject();
                        
            int id = _receiveObjectT.Data;
            bool isSuccess = await _institutionService.DeleteInstitutionAsync(id);
            if (isSuccess)
            {
                _returnObject.Code = 1;
            }
            else
            {
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "删除机构信息失败";
            }
            return _returnObject;
            // return NoContent();
        }
    }
}